package org.xtframe.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xtframe.bean.SystemConfig;
import org.xtframe.dao.DataBaseDao;
import org.xtframe.filter.SecurityFilter;
import org.xtframe.sql.SqlDataVerify;
import org.xtframe.util.SpringUtil;
import org.xtframe.util.StringUtil;
import org.xtframe.util.SystemConfigUtil;

public class ServerData {

	private final Log logger = LogFactory.getLog(getClass());
	
	private DataBaseDao dataBaseDao;
	private SystemConfig systemConfig;
	private SecurityFilter securityFilter;
	
	// 所有角色
	private Map<String, Role> role;
	// 所有菜单
	private ArrayList<Menu> menu;
	// 所有sql
	private Map<String, SQL> sql;
	// 所有逻辑
	private Map<String, Logic> logic;
	// 所有资源
	private Map<String, Res> res;
	// 所有字典数据
	private ArrayList<Dictionary> dictionary;
	// 数据字典
	private Map<String, ArrayList<Map<String, String>>> dicMap;
	// 角色权权
	private ArrayList<Map<String, String>> optRole;
	// 系统数据
	private Map<String, SystemData> systemData;
	// 所有数据库
	private ArrayList<DataBase> dataBase;
	
	public ServerData() {
		dataBaseDao = (DataBaseDao) SpringUtil.getBean("dataBaseDao");
		systemConfig = SystemConfigUtil.getSystemConfig();
		securityFilter = (SecurityFilter) SpringUtil.getBean("securityFilter");
		
		role = new TreeMap<String, Role>();
		menu = new ArrayList<Menu>();
		sql = new TreeMap<String, SQL>();
		logic = new TreeMap<String, Logic>();
		res = new TreeMap<String, Res>();
		dictionary = new ArrayList<Dictionary>();
		dicMap = new TreeMap<String, ArrayList<Map<String, String>>>();
		optRole = new ArrayList<Map<String, String>>();
		systemData = new TreeMap<String, SystemData>();
		dataBase = new ArrayList<DataBase>();
	}
	
	// 初始化
	public boolean initAll(){
		return (initRole() 
				&& initSQL() 
				&& initMenu() 
				&& initLogic() 
				&& initRes() 
				&& initDictionary() 
				&& initSystemData()
				&& initDataBase());
	}
	
	// 角色初始化
	public boolean initRole(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitRoleSql(), null);
			if(result == null) return false;
			role.clear();
			optRole.clear();
			for(Map<String, Object> obj : result){
				Role tem_role = new Role();
				tem_role.setRoleId(StringUtil.toString(obj.get("roleid"), ""));
				tem_role.setRoleName(StringUtil.toString(obj.get("rolename"), ""));
				tem_role.setOrderNo(Integer.valueOf(StringUtil.toString(obj.get("orderno"), "")));
				tem_role.init();
				role.put(tem_role.getRoleId(), tem_role);
				
				Map<String, String> temp = new HashMap<String, String>();
				temp.put("roleId", tem_role.getRoleId());
				temp.put("roleName", tem_role.getRoleName());
				optRole.add(temp);
			}
			logger.info("角色初始化成功！");
			return true;
		} catch (NumberFormatException e) {
			logger.error("角色初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// SQL初始化
	public boolean initSQL(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitSqlSql(), null);
			if(result == null) return false;
			sql.clear();
			for(Map<String, Object> obj : result){
				SQL tem_sql = new SQL();
				tem_sql.setSqlId(StringUtil.toString(obj.get("sqlid"), "").trim());
				tem_sql.setSqlName(StringUtil.toString(obj.get("sqlname"), ""));
				tem_sql.setSysCode(StringUtil.toString(obj.get("syscode"), ""));
				tem_sql.setSqlTemplet(StringUtil.toString(obj.get("sqltemplet"), ""));
				tem_sql.setDataVerify(new SqlDataVerify(tem_sql, StringUtil.toString(obj.get("dataverify"), "")));
				tem_sql.setDbType(StringUtil.toString(obj.get("dbtype"), ""));
				tem_sql.setSortNo(Integer.valueOf(StringUtil.toString(obj.get("sortno"), "")));
				tem_sql.setRemark(StringUtil.toString(obj.get("remark"), ""));
				tem_sql.setModId(Integer.valueOf(StringUtil.toString(obj.get("modid"), "")));
				sql.put("__"+tem_sql.getDbType()+"_"+tem_sql.getSqlId(), tem_sql);
			}
			logger.info("SQL初始化成功！");
			return true;
		} catch (NumberFormatException e) {
			logger.error("SQL初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// 菜单初始化
	public boolean initMenu(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitMenuSql(), null);
			if(result == null) return false;
			menu.clear();
			for(Map<String, Object> obj : result){
				Menu tem_menu = new Menu();
				tem_menu.setMenuId(Integer.valueOf(StringUtil.toString(obj.get("menuid"), "")));
				tem_menu.setMenuName(StringUtil.toString(obj.get("menuname"), ""));
				tem_menu.setMenuIcon(StringUtil.toString(obj.get("menuicon"), ""));
				tem_menu.setMenuType(Integer.valueOf(StringUtil.toString(obj.get("menutype"), "")));
				tem_menu.setAtMenuId(StringUtil.toString(obj.get("atmenuid"), ""));
				tem_menu.setMenuLevel(Integer.valueOf(StringUtil.toString(obj.get("menulevel"), "")));
				tem_menu.setUrl(StringUtil.toString(obj.get("url"), ""));
				tem_menu.setSwfUrl(StringUtil.toString(obj.get("swfurl"), ""));
				tem_menu.setOrderNo(Integer.valueOf(StringUtil.toString(obj.get("orderno"), "")));
				tem_menu.setRemark(StringUtil.toString(obj.get("remark"), ""));
				menu.add(tem_menu);
			}
			logger.info("菜单初始化成功！");
			return true;
		} catch (NumberFormatException e) {
			logger.error("菜单初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// 逻辑初始化
	public boolean initLogic(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitLogicSql(), null);
			if(result == null) return false;
			logic.clear();
			for(Map<String, Object> obj : result){
				Logic tem_logic = new Logic();
				tem_logic.setLogicId(StringUtil.toString(obj.get("logicid"), "").trim());
				tem_logic.setLogicName(StringUtil.toString(obj.get("logicname"), ""));
				tem_logic.setOrderNo(Integer.valueOf(StringUtil.toString(obj.get("orderno"), "")));
				tem_logic.setRemark(StringUtil.toString(obj.get("remark"), ""));
				logic.put(tem_logic.getLogicId(), tem_logic);
			}
			logger.info("逻辑初始化成功！");
			return true;
		} catch (NumberFormatException e) {
			logger.error("逻辑初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// 资源初始化
	public boolean initRes(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitResSql(), null);
			if(result == null) return false;
			res.clear();
			Set<Res> restrictedResources = new HashSet<Res>();
			for(Map<String, Object> obj : result){
				Res tem_res = new Res();
				tem_res.setResId(StringUtil.toString(obj.get("resid"), "").trim());
				tem_res.setResName(StringUtil.toString(obj.get("resname"), ""));
				tem_res.setUri(StringUtil.toString(obj.get("uri"), ""));
				tem_res.setOrderNo(Integer.valueOf(StringUtil.toString(obj.get("orderno"), "")));
				tem_res.setRemark(StringUtil.toString(obj.get("remark"), ""));
				res.put(tem_res.getResId(), tem_res);
				restrictedResources.add(tem_res);
			}
			securityFilter.setRestrictedResources(restrictedResources);
			logger.info("资源初始化成功！");
			return true;
		} catch (NumberFormatException e) {
			logger.error("资源初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// 数据字典初始化
	public boolean initDictionary(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitDictionarySql(), null);
			if(result == null) return false;
			dicMap.clear();
			dictionary.clear();
			for(Map<String, Object> obj : result){
				Dictionary tem_dictionary = new Dictionary();
				tem_dictionary.setDictionaryId(StringUtil.toString(obj.get("dictionaryid"), "").trim());
				tem_dictionary.setParentId(StringUtil.toString(obj.get("parentid"), "").trim());
				tem_dictionary.setDictionaryName(StringUtil.toString(obj.get("dictionaryname"), ""));
				tem_dictionary.setDataValue(StringUtil.toString(obj.get("datavalue"), ""));
				dictionary.add(tem_dictionary);
			}
			logger.info("数据字典初始化成功！");
			return true;
		} catch (Exception e) {
			logger.error("数据字典初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// 系统数据初始化
	public boolean initSystemData(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitSystemDataSql(), null);
			if(result == null) return false;
			systemData.clear();
			for(Map<String, Object> obj : result){
				SystemData tem_systemdata = new SystemData();
				tem_systemdata.setDataName(StringUtil.toString(obj.get("dataname"), "").trim());
				tem_systemdata.setDataValue(StringUtil.toString(obj.get("datavalue"), ""));
				tem_systemdata.setRemark(StringUtil.toString(obj.get("remark"), ""));
				systemData.put(tem_systemdata.getDataName(), tem_systemdata);
			}
			logger.info("系统数据初始化成功！");
			return true;
		} catch (Exception e) {
			logger.error("系统数据初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// 数据库集初始化
	public boolean initDataBase(){
		try {
			List<Map<String, Object>> result = dataBaseDao.executeQuery(systemConfig.getServiceInitDataBaseSql(), null);
			if(result == null) return false;
			dataBase.clear();
			for(Map<String, Object> obj : result){
				DataBase tem_database = new DataBase();
				tem_database.setJndiName(StringUtil.toString(obj.get("jndiname"), "").trim());
				tem_database.setDbName(StringUtil.toString(obj.get("dbname"), ""));
				tem_database.setDbType(StringUtil.toString(obj.get("dbtype"), ""));
				tem_database.setDriverClassName(StringUtil.toString(obj.get("driverclassname"), ""));
				tem_database.setUrl(StringUtil.toString(obj.get("url"), ""));
				tem_database.setUsername(StringUtil.toString(obj.get("username"), ""));
				tem_database.setPassword(StringUtil.toString(obj.get("password"), ""));
				tem_database.setRemark(StringUtil.toString(obj.get("remark"), ""));
				tem_database.init();
				dataBase.add(tem_database);
			}
			logger.info("数据库集初始化成功！");
			return true;
		} catch (Exception e) {
			logger.error("数据库集初始化失败！ "+e.toString());
		}
		return false;
	}
	
	// 根据角色id获取角色对象，无此角色则返回null
	public Role getRole(String roleid){
		return role.get(roleid);
	}
	
	// 根据角色id链表获取角色对象链表，无此角色则返回空对象链表
	public ArrayList<Role> getRoleList(List<String> roleIdList){
		if(roleIdList==null || roleIdList.size()==0) return null;
		ArrayList<Role> roleList = new ArrayList<Role>();
		for(String roleId : roleIdList) {
			Role tem = getRole(roleId);
			if(tem != null) roleList.add(tem);
		}
		return roleList;
	}
	
	// 根据角色id链表获取角色权权链表，无此角色则返回空对象链表
	public ArrayList<Map<String, String>> getOptRoleList(List<String> roleIdList){
		if(roleIdList==null || roleIdList.size()==0) return null;
		ArrayList<Map<String, String>> optRoleList = new ArrayList<Map<String, String>>();
		for(String roleId : roleIdList) {
			for(Map<String, String> temp : optRole) {
				if(temp.get("roleId").equals(roleId)){
					optRoleList.add(temp);
					break;
				}
			}
		}
		return optRoleList;
	}
	
	// 根据菜单id获取菜单对象，无此菜单则返回null
	public Menu getMenu(int menuId){
		if(menu == null) return null;
		Menu result = null;
		for(Menu temp : menu){
			if(temp.getMenuId() == menuId){
				result = temp;
				break;
			}
		}
		return result;
	}
	
	// 根据菜单id链表获取菜单对象链表，无此菜单则返回空对象链表
	public ArrayList<Menu> getMenuList(List<Integer> menuIdList){
		if(menuIdList==null || menuIdList.size()==0) return null;
		ArrayList<Menu> menuList = new ArrayList<Menu>();
		for(Menu temp : menu){
			for(Integer menuId : menuIdList){
				if(temp.getMenuId() == menuId){
					menuList.add(temp);
					break;
				}
			}
		}
		return menuList;
	}
	
	// 根据SQLid获取SQL对象
	public SQL getSql(String sqlId) {
		String dbType = null;
		for(DataBase db : dataBase){
			if(db.isInSQL(sqlId)){
				dbType = db.getDbType();
				break;
			}
		}
		if(dbType == null) dbType = systemConfig.getDbType();
		return sql.get("__"+dbType+"_"+sqlId);
	}
	
	// 根据数据字典编号返回[{"名称","值"}…]的数据链表对象
	public ArrayList<Map<String, String>> getDictionaryDataList(String dictionaryId){
		ArrayList<Map<String, String>> result = dicMap.get(dictionaryId);
		if(result != null) return result;
		
		result = new ArrayList<Map<String, String>>();
		for(Dictionary temp : dictionary){
			if(temp.getParentId().equals(dictionaryId)){
				Map<String, String> dic = new HashMap<String, String>();
				dic.put("dataName", temp.getDictionaryName());
				dic.put("dataValue", temp.getDataValue());
				result.add(dic);
			}
		}
		dicMap.put(dictionaryId, result);
		return result;
	}
	
	// 获取系统数据
	public String getSystemDataValue(String dataName){
		String result = "";
		SystemData sd = systemData.get(dataName);
		if(sd != null) result = sd.getDataValue();
		return result;
	}
	
	public ArrayList<Map<String, String>> getOptRole() {
		return optRole;
	}
	
	public ArrayList<Dictionary> getDictionary() {
		return dictionary;
	}

	public ArrayList<DataBase> getDataBase() {
		return dataBase;
	}
}
